using System;
using System.IO;
using System.Linq;
using ResxHelper.Logic.Formatters;
using ResxHelper.Object;

namespace ResxHelper.Logic.Readers
{
    public class CsvResourceFileReader : IResourceFileReader
    {
        public string Path { get; private set; }

        public CsvResourceFileReader(string path)
        {
            Path = path;
        }

        public ResourceFile Read()
        {
            if (!File.Exists(Path)) return null;

            var csvContent = OpenCsv(Path);
            var resourceFile = ParseResourceFile(csvContent, Path);
            return resourceFile;
        }

        public static ResourceFile ParseResourceFile(string csv, string path)
        {
            if (!File.Exists(path)) return null;

            var resourceFile = new ResourceFile();
            resourceFile.CultureInfo = ResourceFile.ReadCulture(path);
            resourceFile.FilePath = path;

            var rawEntries = csv.Split(new[] { "\n" }, StringSplitOptions.None);

            resourceFile.Entries = new ResourceFileEntryCollection();
            foreach (var entry in rawEntries)
            {
                if (string.IsNullOrEmpty(entry)) continue;
                var entryParts = entry.Split(new[] { "," }, StringSplitOptions.None);

                if (entryParts.Count() != 3)
                    throw new FileLoadException("Comma delimited file was not in the expected format.");

                var tEntry = new ResourceFileEntry
                {
                    Key = entryParts[0],
                    Value = entryParts[1],
                    Comment = entryParts[2]
                };

                resourceFile.Entries.Add(tEntry.Key, tEntry);
            }

            return resourceFile;
        }

        public static string OpenCsv(string path)
        {
            return string.IsNullOrEmpty(path)
                ? string.Empty
                : File.ReadAllText(path);
        }
    }
}
